<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * 后台管理员MODEL
 * @author alang
 *
 */

class Admins_mdl extends CI_Model
{
	
	
	
	const TBL_ADMINS = 'cj_admins';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * 验证用户
	 * @param string $username 
	 * @param string $password
	 * @return array $user
	 */
	
	public function validate_admin($username,$password)
	{
	
		$data = FALSE;
		$this->db->where('txusername',$username);
		$query = $this->db->get(self::TBL_ADMINS);
		if($query->num_rows()==1)
		{
			$data = $query->row_array();
		}
		
		if(!empty($data))
		{
			$data = (Common::hash_Validate($password, $data['txpassword'])) ? $data : FALSE;
		}
		
		$query->free_result();
		
		return $data;
	}
	
	/**
     * 获取单个用户信息
     * 
     * @access public
	 * @param int $uid 用户id
     * @return array - 用户信息
     */
	public function get_admin_by_id($id)
	{
		$data = array();
		
		$this->db->select('*')->from(self::TBL_ADMINS)->where('uid', $id)->limit(1);
		$query = $this->db->get();
		if($query->num_rows() == 1)
		{
			$data = $query->row_array();
		}
		$query->free_result();
		
		return $data;
	}
	
	/**
    * 修改用户信息
    * 
    * @access public
	* @param int - $uid 用户ID
	* @param int - $data 用户信息
	* @param int - $cipher_password 密码是否hash	
    * @return boolean - success/failure
    */	
	public function update_admin($uid, $data, $hashed = TRUE)
	{
		if(!$hashed)
		{
		  $data['password'] = Common::do_hash($data['password']);
		}
		
		$this->db->where('uid', intval($uid));
		$this->db->update(self::TBL_ADMINS, $data);
		
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	/**
	 * 取得用户列表
	 * @access public
	 * @param bool $page - 是否分页
	 * @param int $limit - 每页显示条数
	 * @param int $office - 起始数
	 * @param string $order - 排序
	 * @param array
	 */
	
	public function get_all_admin($page = true,$limit = 0, $offset = 0, $order = 'DESC')
	{
		if($page)
		{
			$this->db->limit(intval($limit));
			$this->db->offset(intval($offset));
			return $this->db->get(self::TBL_ADMINS)->result();
		}
		else 
		{
			return $this->db->get(self::TBL_ADMINS)->result();		
		}
	}
	
	/**
	 * 添加用户
	 * @param array $user
	 * @return bool
	 */
	public function add_admin($admin)
	{
		$this->db->insert(self::TBL_ADMINS,$admin);
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	/**
	 * 删除用户
	 * @param int $uid
	 */
	public function del_admin($uid)
	{
		$this->db->delete(self::TBL_ADMINS, array('uid' => $uid)); 
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	/**
	 * 
	 * 取得REWARD数 ...
	 * @return int num
	 */
	
	public function get_admin_count()
	{
		$count = 0;
		$count =  $this->db->count_all(self::TBL_ADMINS);
		return $count;
	}
	
	
	
	
	
}
